package org.csu.canteen.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.csu.canteen.service.CartItemService;
import org.csu.canteen.service.CartService;
import org.csu.canteen.service.CouponService;
import org.csu.canteen.service.Impl.AccountServiceImpl;
import org.csu.canteen.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private AccountServiceImpl accountService;
    public CommonController() {

    }

    @GetMapping("/bottom")
    public String bottom(@RequestParam("username") String username, Model model) {
        AccountVO loginAccount = accountService.getAccountByUsername(username);
        model.addAttribute("loginAccount", loginAccount);
        return "common/bottom"; // 对应 Thymeleaf 视图
    }

    @GetMapping("/top")
    public String top(HttpSession session, Model model) {
        AccountVO loginAccount = (AccountVO) session.getAttribute("loginAccount");
        model.addAttribute("loginAccount", loginAccount);
        return "common/top";
    }

    @GetMapping("/countDownToLogin")
    public String countDownToLogin(HttpServletRequest request, Model model) {
        model.addAttribute("contextPath", request.getContextPath());
        return "common/countDownToLogin"; // 对应 Thymeleaf 视图
    }

    @GetMapping("/countDownToOrder")
    public String countDownToOrder(@RequestParam("username") String username, Model model) {
        AccountVO loginAccount = accountService.getAccountByUsername(username);
        model.addAttribute("loginAccount", loginAccount);
        return "common/countDownToOrder"; // 对应 Thymeleaf 视图
    }

    @GetMapping("/error")
    public String errorPage(@RequestParam("username") String username, Model model) {
        AccountVO loginAccount = accountService.getAccountByUsername(username);
        model.addAttribute("loginAccount", loginAccount);
        return "common/error"; // 对应 Thymeleaf 视图
    }
    @GetMapping("/signOut")
    public String signOut(HttpSession session, RedirectAttributes redirectAttributes) {
        // 清除会话中的属性
        session.removeAttribute("loginAccount");
        session.removeAttribute("order");
        session.removeAttribute("cart");

        // 可以添加一个属性来向前端显示注销成功的信息
        redirectAttributes.addFlashAttribute("message", "You have successfully logged out.");

        // 重定向到首页（使用 Thymeleaf 渲染页面）
        return "redirect:/catalog/index";
    }
}